package com.bonc.common.utils;

import java.net.SocketTimeoutException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
 * @author weixiaoguang
 * @email weixiaoguang@bonc.com.cn
 * @date 2021-11-09 9:38 下午
 */
public class HttpUtil {

    static public String httpPost( HttpContext localContext, String url, List<NameValuePair> formparams, 	Map mapHeader, String sCharSet,int timeout) throws Exception
    {
        long beginTime = System.currentTimeMillis();
        System.out.println("httpPost begin : url=" + url);

        HttpClient client = new DefaultHttpClient();

        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, sCharSet );
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);

            // post.setRequestHeader("Content-type", "text/xml; charset=GBK");
            if(mapHeader != null )
            {
                Set set =mapHeader.entrySet();
                Iterator it=set.iterator();
                while(it.hasNext())
                {
                    Map.Entry<String, String>  entry=(Map.Entry<String,String>)it.next();
                    //System.out.println(entry.getKey()+":"+entry.getValue());
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }

            client.getParams().setIntParameter("http.socket.timeout",1000*timeout);

            HttpResponse response = client.execute(post, localContext);
            int iStatusCode = response.getStatusLine().getStatusCode();

            long netTime = System.currentTimeMillis() -   beginTime ;

            System.out.println("httpPost 耗时 : " +  netTime + " ; url=" + url);

            System.out.println("iStatusCode = " +  iStatusCode);

            if( iStatusCode != HttpStatus.SC_OK  &&
                    iStatusCode != HttpStatus.SC_MOVED_PERMANENTLY &&
                    iStatusCode != HttpStatus.SC_MOVED_TEMPORARILY  &&
                    iStatusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR &&
                    iStatusCode != HttpStatus.SC_NOT_FOUND )
            {
                System.out.println(response.getStatusLine().getStatusCode());
                throw new RuntimeException(" http post error");
            }

            if( iStatusCode == HttpStatus.SC_MOVED_TEMPORARILY  )
            {
                System.out.println("302");
                HttpEntity resEntity =  response.getEntity();
                String ret= (resEntity == null) ? null : EntityUtils.toString(resEntity, sCharSet  );
                System.out.println("302 ret  = " + ret);

                Header header = response.getFirstHeader("location");
                String newUri= header.getValue(); // 这就是跳转后的地址，再向这个地址发出新申请，以便得到跳转后的信息是啥。

                System.out.println("new Uri = " + newUri);

                return newUri;
            }

            if(  iStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR )
            {
                return "服务器内部错误，响应码： " + iStatusCode;
            }

            if(  iStatusCode == HttpStatus.SC_NOT_FOUND)
            {
                return "找不到链接，响应码： " + iStatusCode;
            }

            HttpEntity resEntity =  response.getEntity();
            return (resEntity == null) ? null : EntityUtils.toString(resEntity, HTTP.UTF_8  );

        } catch(SocketTimeoutException e){
            throw new Exception("网络超时");
        }
        catch(Exception e){
            throw new Exception(e.getMessage());
        }
    }

    static public String httpPostJsonOrXml( HttpContext localContext, String url, String content, 	Map mapHeader, String sCharSet,int timeout) throws Exception
    {
        long beginTime = System.currentTimeMillis();
        System.out.println("httpPost begin : url=" + url);

        HttpClient client = new DefaultHttpClient();

        try {
            StringEntity entity = new StringEntity(content, sCharSet );
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);

            // post.setRequestHeader("Content-type", "text/xml; charset=GBK");
            if(mapHeader != null )
            {
                Set set =mapHeader.entrySet();
                Iterator it=set.iterator();
                while(it.hasNext())
                {
                    Map.Entry<String, String>  entry=(Map.Entry<String,String>)it.next();
                    //System.out.println(entry.getKey()+":"+entry.getValue());
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }

            client.getParams().setIntParameter("http.socket.timeout",1000*timeout);

            HttpResponse response = client.execute(post, localContext);
            int iStatusCode = response.getStatusLine().getStatusCode();

            long netTime = System.currentTimeMillis() -   beginTime ;

            System.out.println("httpPost 耗时 : " +  netTime + " ; url=" + url);

            System.out.println("iStatusCode = " +  iStatusCode);

            if( iStatusCode != HttpStatus.SC_OK  &&
                    iStatusCode != HttpStatus.SC_MOVED_PERMANENTLY &&
                    iStatusCode != HttpStatus.SC_MOVED_TEMPORARILY  &&
                    iStatusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR &&
                    iStatusCode != HttpStatus.SC_NOT_FOUND )
            {
                System.out.println(response.getStatusLine().getStatusCode());
                throw new RuntimeException(" http post error");
            }

            if( iStatusCode == HttpStatus.SC_MOVED_TEMPORARILY  )
            {
                System.out.println("302");
                HttpEntity resEntity =  response.getEntity();
                String ret= (resEntity == null) ? null : EntityUtils.toString(resEntity, sCharSet  );
                System.out.println("302 ret  = " + ret);

                Header header = response.getFirstHeader("location");
                String newUri= header.getValue(); // 这就是跳转后的地址，再向这个地址发出新申请，以便得到跳转后的信息是啥。

                System.out.println("new Uri = " + newUri);

                return newUri;
            }

            if(  iStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR )
            {
                return "服务器内部错误，响应码： " + iStatusCode;
            }

            if(  iStatusCode == HttpStatus.SC_NOT_FOUND)
            {
                return "找不到链接，响应码： " + iStatusCode;
            }

            HttpEntity resEntity =  response.getEntity();
            return (resEntity == null) ? null : EntityUtils.toString(resEntity, HTTP.UTF_8  );

        } catch(SocketTimeoutException e){
            throw new Exception("网络超时");
        }
        catch(Exception e){
            throw new Exception(e.getMessage());
        }
    }

    static public String httpGet( HttpContext localContext, String url, Map header, String sCharSet,int timeout) throws Exception
    {
        long beginTime = System.currentTimeMillis();
        System.out.println("httpGet begin : url=" + url);

        HttpClient client = new DefaultHttpClient();

        try {
            HttpGet get = new HttpGet(url);
            if(header != null )
            {
                Set set =header.entrySet();
                Iterator it=set.iterator();
                while(it.hasNext())
                {
                    Map.Entry<String, String>  entry=(Map.Entry<String,String>)it.next();
                    System.out.println(entry.getKey()+":"+entry.getValue());
                    get.addHeader(entry.getKey(), entry.getValue());
                }
            }

            client.getParams().setIntParameter("http.socket.timeout",1000*timeout);
            HttpResponse response = client.execute(get, localContext);
            int iStatusCode = response.getStatusLine().getStatusCode();

            long netTime = System.currentTimeMillis() -   beginTime ;
            //log.debug("httpGet 耗时 : " +  netTime + " ; url=" + url);

            if( iStatusCode != HttpStatus.SC_OK  &&
                    iStatusCode != HttpStatus.SC_MOVED_PERMANENTLY &&
                    iStatusCode != HttpStatus.SC_MOVED_TEMPORARILY  &&
                    iStatusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR &&
                    iStatusCode != HttpStatus.SC_NOT_FOUND )
            {
                System.out.println(response.getStatusLine().getStatusCode());
                throw new Exception("异常 返回码 " + iStatusCode);
            }

            if( iStatusCode == HttpStatus.SC_MOVED_TEMPORARILY  )
            {
                return "服务器跳转，返回码：  " + iStatusCode;
            }

            if(  iStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR )
            {
                return "服务器返回错误，错误码 ：" + iStatusCode;
            }

            if(  iStatusCode == HttpStatus.SC_NOT_FOUND)
            {
                return "链接不存在，错误码 ：" + iStatusCode;
            }

            HttpEntity resEntity =  response.getEntity();
            return (resEntity == null) ? null : EntityUtils.toString(resEntity, sCharSet  );

        }catch(Exception e){
            throw new Exception(e.getMessage());
        }
    }
}